// BAM Model based on Hare et al.

// Data
data {
  int<lower=0> J; // Number of coders 
  int<lower=0> N; // Number of parties
  int<lower=0> nobs; // Number of observations in long data
  int<lower=0> ctry[nobs]; // country ID number
  int<lower=0> pty[nobs]; // Party ID number
  int<lower=0> id[nobs]; // Coder ID
  real place[nobs]; // Party placements
}

parameters {
  real<lower=-1.3, upper=-1.2> Z_1; // First stimuli (anchored negative) 
  real<lower= 1.2, upper= 1.3> Z_2; // Second stimuli (anchored positive)
  real Z_rest[N-2]; // Remaining stimuli
  real alpha[J]; // Shift parameters
  real beta[J];  // Stretch parameters
  real<lower=0> sigma_global;
  vector[J] sigma_j_raw;
  vector[N] sigma_n_raw;
  real<lower=0> tau_j;  // Scale for coder variance
  real<lower=0> tau_n;  // Scale for party variance

}

transformed parameters {
  real Z[N];
  // Combine stimuli into a single vector
  Z[1] = Z_1;
  Z[2] = Z_2;
  Z[3:N] = Z_rest;
  
  // Error term
  vector<lower=0>[J] sigma_j;
  vector<lower=0>[N] sigma_n;
  vector<lower=0>[nobs] sigma;
  
  // Non-centered parameterization
  sigma_j = sigma_global * exp(tau_j * sigma_j_raw);
  sigma_n = sigma_global * exp(tau_n * sigma_n_raw);
  
  for(k in 1:nobs){
    sigma[k] = sqrt(square(sigma_j[id[k]]) + square(sigma_n[pty[k]]));   
  }
}


model {
  // Estimuli priors
  Z_1 ~ normal(-1.25, 0.1); // Centered near -1.25
  Z_2 ~ normal(1.25, 0.1); // Centered near 1.22
  Z_rest ~ normal(0, 1);
  // Stretch and Shift Parameters Priors
  alpha ~ uniform(-100, 100); // Noninformative uniform prior Equation (5)
  beta ~ uniform(-100, 100); // Noninformative uniform prior Equation (5)
  // Priors for variance components
  sigma_global ~ normal(0, 2);
  tau_j ~ normal(0, 1);
  tau_n ~ normal(0, 1);
  sigma_j_raw ~ normal(0, 1);
  sigma_n_raw ~ normal(0, 1);
  
  //Model
  for(k in 1:nobs){
    place[k] ~ normal(alpha[id[k]] + beta[id[k]] * Z[pty[k]],  sigma[k]);  
  }
}